
package com.haohope.framework.ureport2;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import com.bstek.ureport.provider.report.ReportFile;
import com.bstek.ureport.provider.report.ReportProvider;

public abstract class AbstractUreport2Provider implements ReportProvider{
	private final AbstractUreport2Service ureport2Service;
	public AbstractUreport2Provider(AbstractUreport2Service ureport2Service) {
		this.ureport2Service = ureport2Service;
	}
	public abstract String getFileStorePrefix();
	public abstract String getFileStoreName();
	@Override
    public String getPrefix() {
        return getFileStorePrefix();
    }
	@Override
    public String getName() {
		return getFileStoreName();
	}
	@Override
    public boolean disabled() {
		return false;
    }
	@Override
    public InputStream loadReport(String file) {
		if(file.startsWith(getPrefix())) {
			  file = file.replaceFirst(getPrefix(), "");
		}
		Ureport2File ureportFile = ureport2Service.getFile(getPrefix(), file);
		return new ByteArrayInputStream(ureportFile.getFilecontent().getBytes());
    }
	@Override
	public List<ReportFile> getReportFiles() {
		List<ReportFile> list=new ArrayList<ReportFile>();
		List<Ureport2File> list1 = ureport2Service.getFiles(getPrefix());
		for(Ureport2File f:list1) {
			list.add(new ReportFile(f.getFilename(),null!=f.getUpdatetime()?f.getUpdatetime():f.getCreatetime()));
		}
        Collections.sort(list, new Comparator<ReportFile>(){
            @Override
            public int compare(ReportFile f1, ReportFile f2) {
                return f2.getUpdateDate().compareTo(f1.getUpdateDate());
            }
        });
        return list;
	}
	@Override
    public void deleteReport(String file) {
		if(file.startsWith(getPrefix())) {
			file = file.replaceFirst(getPrefix(), "");
		}
		ureport2Service.deleteFile(getPrefix(), file);
    }
	@Override
	public void saveReport(String file,String content) {
	  // ureport2Service.saveReport(getPrefix(), file, content);
	  if(file.startsWith(getPrefix())) {
		  file = file.replaceFirst(getPrefix(), "");
	  }
	  Ureport2File ureportFile = new Ureport2File();
	  ureportFile.setDeleteflag(false);
	  ureportFile.setFilename(file);
	  ureportFile.setFilecontent(content);
	  ureportFile.setPrefix(getPrefix());
	  ureportFile.setCreatetime(new Date());
	  ureport2Service.saveFile(ureportFile);
	}
}
